/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package de.scrum4j.service;

import de.scrum4j.domain.Project;
import de.scrum4j.domain.Sprint;
import de.scrum4j.domain.UserStory;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.ejb.HibernateEntityManager;

/**
 *
 * @author LOD
 */
@Stateless
public class ScrumItBean implements ScrumItBeanRemote
{
   @PersistenceContext
   private EntityManager m_em;

   @Override
   public Project getProject(final long projectID)
   {
      return (Project) getSession().get(Project.class, projectID);
   }

   @Override
   public Sprint getSprint(final long sprintID)
   {
      return (Sprint) getSession().get(Sprint.class, sprintID);
   }

   @Override
   public UserStory getUserStory(final long userStoryID)
   {
      return (UserStory) getSession().get(UserStory.class, userStoryID);
   }

   @Override
   public Project store(Project project)
   {
      project = (Project) getSession().merge(project);
      getSession().saveOrUpdate(project);      
      return project;
   }

   @Override
   public Sprint store(Sprint sprint)
   {
      sprint = (Sprint) getSession().merge(sprint);
      getSession().saveOrUpdate(sprint);      
      return sprint;
   }

   @Override
   public void delete(Project entity)
   {
      entity = (Project) getSession().merge(entity);
      getSession().delete(entity);
   }

   @Override
   public void delete(UserStory entity)
   {
      entity = (UserStory) getSession().merge(entity);
      getSession().delete(entity);
   }

   @Override
   public void delete(Sprint entity)
   {
/*      for (UserStory userStory : entity.getUserStories())
      {
         userStory.setSprint(null);
      }
      getSession().saveOrUpdate(entity);
 
 */
      entity = (Sprint) getSession().merge(entity);
      getSession().delete(entity);
   }

   protected Session getSession()
   {
      return (((HibernateEntityManager) m_em.getDelegate())).getSession();
   }
}
